package cn.tedu.rabbitmq.test.dlx;

import com.rabbitmq.client.*;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class DelayConsumer {
    //连接客户端
    private Channel channel;
    @Before
    public void init() throws IOException, TimeoutException {
        //通过java客户端建立和rabbitmq的连接
        ConnectionFactory factory=new ConnectionFactory();
        //给工厂提供链接属性 ip:port
        factory.setHost("192.168.8.100");
        factory.setPort(5672);
        //权限账号 admin/123456
        factory.setUsername("admin");
        factory.setPassword("123456");
        //虚拟主机,每隔连接工厂,由一个程序管理,程序所属的环境 连接的虚拟主机 virtual_host不同
        //实现不同环境的数据隔离 默认就是/
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        //可以从长连接获取短链接
        channel = connection.createChannel();
    }
    @Test
    public void consumer() throws IOException {
        channel.basicConsume("dlx_queue",true,(consumerTag, message) -> {
                    System.out.println("消费者1接收到消息");
                    byte[] body = message.getBody();
                    String msg=new String(body);
                    System.out.println("收到消息数据:"+msg);
                    System.out.println("消费时间:" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                },consumerTag -> {
                    System.out.println("消费取消");
                });
        while(true);
    }
    @Test
    public void consumer01() throws IOException {
        channel.basicConsume("biz_queue",false,(consumerTag, message) -> {
            System.out.println("消费者2接收到消息");
            byte[] body = message.getBody();
            String msg=new String(body);
            System.out.println("收到消息数据:"+msg);
            System.out.println("消费时间:" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
        },consumerTag -> {
            System.out.println("消费取消");
        });
        while(true);
    }
}